<template>
  <t-dialog
    :header="this.header"
    :visible.sync="visible"
    :onClose="closeDialog"
    :closeOnOverlayClick="false"
    @confirm="onSubmit"
    :confirmBtn="{
        content: loading?'提交中...':'确认',
        theme: 'primary',
        loading: loading,
      }"
    width="50%"
    top="5%"
  >
   <div style="height: 65vh">
     <t-form ref="form" :colon="true"  :data="formData" labelWidth="100px" :rules="rules">
       <t-form-item label="上级名称" name="parentId">
         <t-tree-select clearable filterable :treeProps="{keys: {value: 'id'}}" placeholder="无上级可不选" v-model="formData.parentId"
                        :data="menuOptions"/>
       </t-form-item>
       <t-form-item label="名称" name="name">
         <t-input clearable v-model="formData.name" placeholder="请输入"/>
       </t-form-item>
       <t-form-item label="类型" name="type">
         <t-radio-group v-model="formData.type" :options="dict.type.road_data_type"></t-radio-group>
       </t-form-item>
       <t-form-item label="编号" name="code">
         <t-input clearable v-model="formData.code" placeholder="请输入"/>
       </t-form-item>
       <t-form-item label="起点桩号" name="startNum">
         <t-input clearable v-model="formData.startNum" placeholder="请输入"/>
       </t-form-item>
       <t-form-item label="终点桩号" name="endNum">
         <t-input clearable v-model="formData.endNum" placeholder="请输入"/>
       </t-form-item>
       <t-form-item label="里程" name="legend">
         <t-input-adornment  append="KM">
           <t-input-number style="width: calc(390px - 36px)"  :allowInputOverLimit="false" theme="normal" clearable v-model="formData.legend" :min="0"
                           placeholder="请输入"/>
         </t-input-adornment>
       </t-form-item>
       <t-form-item  label="通车时间" name="startDate">
         <t-date-picker filterable mode="month" style="width:390px" clearable v-model="formData.startDate"></t-date-picker>
       </t-form-item>
       <t-form-item help="搜索不到请切换内外部单位" v-if="!['1','2'].includes(formData.type)" label="管养单位" name="managerDept">
         <t-tree-select v-if="formData.isInnerCompany==='1'" style="width:390px" clearable filterable
                        :treeProps="{keys: {value: 'label'}}" v-model="formData.managerDept" :data="deptMenuOptions"
                        placeholder="选择单位">
           <template #label>
             <t-switch
               size="medium"
               v-model="formData.isInnerCompany"
               :label="['内部', '外部']"
               :customValue="['1', '0']"
               @change="()=>{formData.managerDept=''}"
             ></t-switch>
           </template>
         </t-tree-select>
         <t-select
           v-else
           v-model="formData.managerDept"
           creatable
           filterable
           placeholder="请输入"
           :loading="companyLoading"
           @search="remoteCompanyMethod"
           :options="companyOptions"
           @create="createCompanyOptions"
           style="width: 390px"
         >
           <template #label>
             <t-switch
               size="medium"
               v-model="formData.isInnerCompany"
               :label="['内部', '外部']"
               :customValue="['1', '0']"
               @change="()=>{formData.managerDept=''}"
             ></t-switch>
           </template>
         </t-select>
       </t-form-item>
       <t-form-item label="显示排序" name="sort">
         <t-input-number clearable v-model="formData.sort" :min="1" placeholder="请输入"/>
       </t-form-item>
     </t-form>
   </div>
  </t-dialog>
</template>

<script>
export default {
  name: "add-edit-expressway",
  props: ['header', 'objId', 'parentId'],
  dicts: ["road_data_type"],
  data() {
    return {
      companyLoading: false,
      companyOptions: [],
      rules: {
        // parentId: [
        //   { required: true, message: "上级专业不能为空" }
        // ],
        name: [
          {required: true, message: "公路名称不能为空"}
        ],
        type: [
          {required: true, message: "类型不能为空"}
        ],
        code: [
          {required: true, message: "编号不能为空"}
        ],
        sort: [
          {required: true, message: "显示排序不能为空"}
        ],
        startNum: [
          {required: true, message: "起点桩号不能为空"}
        ],
        endNum: [
          {required: true, message: "终点桩号不能为空"}
        ],
        startDate: [
          {required: true, message: "通车时间不能为空"}
        ],
        legend: [
          {required: true, message: "里程不能为空"}
        ],
        managerDept: [
          {required: true, message: "管理单位不能为空"}
        ],
      },
      deptMenuOptions: [],
      menuOptions: [],
      visible: true,
      loading: false,
      formData: {
        isInnerCompany: '1',
        parentId: null,
        name: "",
        type: '1',
        code: '',
        startNum: '',
        endNum: '',
        sort: 1,
        legend: '',
        startDate: '',
        managerDept: '',
      }
    }
  },
  watch: {
    objId: {
      immediate: true,
      handler(val) {
        if (val) {
          this.getObj();
        }
      }
    },
    parentId: {
      immediate: true,
      handler(val) {
        if (val) {
          this.formData.parentId = val;
        }
      }
    }
  },
  created() {
    if (!this.objId) {
      Promise.all([this.getTreeSelect(), this.getDeptTreeSelect()]);
    }
  },
  methods: {
    createCompanyOptions(value){
      this.companyOptions.push({
        label:`${value}`,
        value,
      });
    },
    remoteCompanyMethod(search){
      this.companyLoading = true;
      this.$api.system.dept.selectAllOutDeptList({deptName:search}).then(response => {
        this.companyOptions = response.data.map(val=>  ({
          ...val,
          label:`${val.deptName}`,
          value:val.deptName,
        }));
        this.companyLoading = false;
      }).catch((e) => {
        this.companyLoading = false;
        this.$message.error(e.toString());
      });
    },
    async getObj() {
      await Promise.all([this.getTreeSelect(), this.getDeptTreeSelect()]);
      this.$api.system.expressway.get(this.objId).then(response => {
        if (response.data.parentId === 0) {
          response.data.parentId = null;
        }
        this.formData = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    onSubmit() {
      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {
          this.loading = true;
          if (this.objId) {
            let {parentId} = this.formData;
            if (this.deptId === this.formData.parentId) {
              parentId = 0;
            }
            const row = {...this.formData, parentId}
            this.$api.system.expressway.update(row).then(() => {
              this.$message.success("修改成功");
              this.$emit("reload");
              this.$emit("update:visible", false);
              this.loading = false;
            }).catch((e) => {
              this.loading = false;
              this.$message.error(e.toString());
            });
          } else {
            let {parentId} = this.formData;
            if (!this.formData.parentId) {
              parentId = 0;
            }
            const row = {...this.formData, parentId}
            this.$api.system.expressway.add(row).then((response) => {
              this.$message.success("新增成功");
              this.$emit("reload");
              this.$emit("update:visible", false);
              this.loading = false;
            }).catch((e) => {
              this.loading = false;
              this.$message.error(e.toString());
            });
          }
        }
      });
    },
    getDeptTreeSelect() {
      return this.$api.system.dept.treeSelectAllIn().then(response => {
        this.deptMenuOptions = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    closeDialog() {
      this.$emit("update:visible", false);
    },
    /** 查询菜单下拉树结构 */
    getTreeSelect() {
      return this.$api.system.expressway.treeSelect().then(response => {
        this.menuOptions = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
  }
}
</script>
